package com.by.exceptionhandler;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
@SuppressWarnings("all")
public class GlobalExceptionHandler {
	private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {
    		AuthorizationException.class,
		    UnauthorizedException.class,
		    AuthenticationException.class
    })
    public String unauthorizedMethod(HttpServletRequest request, HttpServletResponse response,AuthorizationException ex) throws IOException {

	    if (!"XMLHttpRequest".equalsIgnoreCase(request
			    .getHeader("X-Requested-With"))) {// 不是ajax请求
		    log.debug("请求无权限");
		    return "/403";
	    } else {
		    // 请求被拦截后直接返回json格式的响应数据
		    String path = request.getRequestURI();
		    response.setCharacterEncoding("utf-8");
		    response.setContentType("application/json");
		    PrintWriter out = response.getWriter();
		    out.println("{\"code\":403,\"success\":false,\"message\":\"访问被拒绝,请联系管理员!\",\"path\":\""+path+"\"}");
		    out.flush();
		    out.close();
	    }
	    return "/403";
    }

    //@ExceptionHandler(value = MaxUploadSizeExceededException.class)


}
